/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.MD5;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * @author ETCORE GroupTalk Developers
 * 
 */
public class UploadAvatarAction extends AbstractAction {
	public static final int UPLOAD_ALLOWED = 2;
	public static final int ACCESS_ALLOWED = 1;
	public static final int ACCESS_ERROR = 0;
	public static final String CMD = "cmd";
	public static final String UPLOAD_AVATAR = "uploadAvatar";

	/**
	 * 
	 */
	private static final long serialVersionUID = 6201619075280929516L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * etcore.webapp.grouptalk.controller.action.AbstractAction#enablePostLoad()
	 */
	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * etcore.webapp.grouptalk.controller.action.AbstractAction#execute(int,
	 * javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		if (UPLOAD_ALLOWED == validationResult) {

			try {
				addAvatar(request);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * etcore.webapp.grouptalk.controller.action.AbstractAction#getForward(javax
	 * .servlet.http.HttpServletRequest, int)
	 */
	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub
		if (validationResult == ACCESS_ALLOWED)
			return PageConstants.PAGE_PATH_AVATAR;
		else if (validationResult == UPLOAD_ALLOWED)
			return "/group/uploadAvatar.action?cmd=uploadDone";
		return PageConstants.ACTION_PATH_ERROR;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * etcore.webapp.grouptalk.controller.action.AbstractAction#getRedirect(
	 * javax.servlet.http.HttpServletRequest, int)
	 */
	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * etcore.webapp.grouptalk.controller.action.AbstractAction#isForward(int)
	 */
	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * etcore.webapp.grouptalk.controller.action.AbstractAction#validate(javax
	 * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("session_user");
		String cmd=request.getParameter(CMD);
		if (user != null&&UPLOAD_AVATAR.equals(cmd))
			return UPLOAD_ALLOWED;
		else if(user!=null)
			return ACCESS_ALLOWED;
		return ACCESS_ERROR;
	}

	public void addAvatar(HttpServletRequest request) throws IOException {

		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("session_user");
		if (user != null) {

			String lang = (String) session.getAttribute("lang");

			try {

				UserService userSevice = new UserService();
				String webInfPath = this.getServletConfig().getServletContext()
						.getRealPath("WEB-INF");
				String rootWebPath = webInfPath.substring(0,
						webInfPath.indexOf("WEB-INF"));
				String uploadPath = rootWebPath
						+ PageConstants.USER_AVATAR_PATH;
				String tempPath = rootWebPath + PageConstants.UPLOAD_TEMP_PATH;

				String attached = null;
				String name = null;
				String fileName = null;

				if (!new File(uploadPath).isDirectory())
					new File(uploadPath).mkdirs();
				if (!new File(tempPath).isDirectory())
					new File(tempPath).mkdirs();
				DiskFileUpload fileUpload = new DiskFileUpload();

				fileUpload.setSizeMax(10 * 1024 * 1024);

				fileUpload.setSizeThreshold(4096);

				fileUpload.setRepositoryPath(tempPath);

				@SuppressWarnings("rawtypes")
				List items = fileUpload.parseRequest(request);
				@SuppressWarnings("rawtypes")
				Iterator itemIterator = items.iterator();

				while (itemIterator.hasNext()) {
					FileItem fi2 = (FileItem) itemIterator.next();

					if (!fi2.isFormField()) {
						int fileError = 0;
						fileName = fi2.getName();
						if (fileName != null)
							fileName = fileName
									.substring(fileName
											.lastIndexOf(Symbols.DOUBLE_BACK_SLASH) + 1);
						if (fileName == null || fileName.equals(Symbols.BLANK))
							fileError = 1;
						String suffixName = null;
						if (fileError != 1) {
							suffixName = Symbols.DOT
									+ fileName.substring(fileName
											.lastIndexOf(Symbols.DOT) + 1);
							MD5 md5 = new MD5();
							fileName = md5.getMD5ofStr(user.getUserName())
									+ suffixName;
							if (name == null || "".equals(name.trim())) {
								name = fileName;
							}

							attached = PageConstants.USER_AVATAR_PATH
									+ fileName;
							File savedFile = new File(uploadPath, fileName); //

							fi2.write(savedFile);//

							BufferedImage image = ImageIO.read(new File(
									uploadPath, fileName));
							int width = image.getWidth();
							int height = image.getHeight();
							request.setAttribute("width", width);
							request.setAttribute("height", height);

						}

					}
				}

				user.setAvatar(attached);

				userSevice.merge(user);
				session.setAttribute(PageConstants.SESSIONUSER, user);

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(Messages.MSG, msg);
			} catch (Exception e) {

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_UPLOAD_ERROR);
				} else {
					msg = Messages.getLabel(Messages.MSG_UPLOAD_ERROR);
				}
				request.setAttribute(Messages.MSG, msg);

				e.printStackTrace();
				return;
			}

		}
	}

	/* (non-Javadoc)
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces=new ArrayList<String>();
		namespaces.add(MessageNamespaces.MY_PROFILE);
		return namespaces;
	}
}
